package com.iqilu.ksd.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.activity.ADActivity;
import com.iqilu.ksd.activity.AddSubscribeActivity;
import com.iqilu.ksd.activity.GalleryActivity;
import com.iqilu.ksd.activity.LiveActivity;
import com.iqilu.ksd.activity.LoginActivity;
import com.iqilu.ksd.activity.MainActivity;
import com.iqilu.ksd.activity.MyActivity;
import com.iqilu.ksd.activity.NewsDetailActivity;
import com.iqilu.ksd.activity.PaikeActivity;
import com.iqilu.ksd.adapter.SubsAdapter;
import com.iqilu.ksd.bean.NewsItemBean;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.NewsType;
import com.iqilu.ksd.constant.UserInfo;
import com.iqilu.ksd.event.ChangeUserInfoEvent;
import com.iqilu.ksd.utils.BoxUtils;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.SPUtils;
import com.iqilu.ksd.view.SubsHeaderView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import okhttp3.Call;

/**
 * 订阅fragment
 * Created by Coofee on 2016/11/17.
 */

public class SubsFragment extends BaseFragment {

    private static final String TAG = "SubsFragment";

    private int page;
    private ArrayList<NewsItemBean> list;
    private SubsAdapter adapter;
    private SubsHeaderView headerView;

    private ImageView btLeft;
    private ImageView btRight;
    private TextView tvTitle;
    private XRefreshView xRefreshView;
    private RecyclerView rvList;
    private RelativeLayout layLoading;
    private RelativeLayout layEmpty;
    private Button btAdd;

    private static final int REQUEST_LOGIN = 1001;
    private static final int REQUEST_ADD = 1002;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_subs, null);
        btLeft = getView(view, R.id.bt_left);
        btRight = getView(view, R.id.bt_right);
        btLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ((MainActivity) getActivity()).openDrawer();
            }
        });
        btRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(context, MyActivity.class));
            }
        });
        tvTitle = getView(view, R.id.tv_title);
        tvTitle.setText(getString(R.string.menu_subs));
        setZHTypeface(tvTitle);
        xRefreshView = getView(view, R.id.xRefreshView);
        rvList = getView(view, R.id.rv_list);
        layLoading = getView(view, R.id.lay_loading);
        layLoading.setVisibility(View.VISIBLE);
        layEmpty = getView(view, R.id.lay_empty);
        btAdd = getView(view, R.id.bt_add);
        btAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                add();
            }
        });
        final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        rvList.setLayoutManager(layoutManager);
        adapter = new SubsAdapter(context);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(context));
        adapter.setOnItemClickListener(onItemClickListener);
        rvList.setAdapter(adapter);

        xRefreshView.setPullRefreshEnable(true);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.enableReleaseToLoadMore(true);
        xRefreshView.enableRecyclerViewPullUp(true);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                super.onRefresh();
                page = 1;
                getList();
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page++;
                getList();
            }
        });
        page = 1;
        getList();
        return view;
    }

    private SubsAdapter.OnItemClickListener onItemClickListener = new SubsAdapter.OnItemClickListener() {
        @Override
        public void OnItemClickListener(View view, int position) {
            Intent intent = null;
            NewsItemBean item = list.get(position - 1);
            if (item.getType().equals(NewsType.ARTICLE)) {
                intent = new Intent(context, NewsDetailActivity.class);
                intent.putExtra("id", item.getId());
                intent.putExtra("catId", item.getCatid());
            } else if (item.getType().equals(NewsType.GALLERY)) {
                intent = new Intent(context, GalleryActivity.class);
                intent.putExtra("id", item.getId());
                intent.putExtra("catId", item.getCatid());
                intent.putExtra("position", 0);
            } else if (item.getType().equals(NewsType.AD) || item.getType().equals(NewsType.URL)) {
                intent = new Intent(context, ADActivity.class);
                intent.putExtra("title", item.getTitle());
                intent.putExtra("type", item.getType());
                intent.putExtra("adUrl", item.getUrl());
                if (item.getType().equals(NewsType.AD)) {
                    intent.putExtra("shareicon", item.getShareicon());
                } else {
                    intent.putExtra("thumb", item.getThumb());
                }
            } else if (item.getType().equals(NewsType.LIVE)) {
                intent = new Intent(context, LiveActivity.class);
                intent.putExtra("id", item.getId());
            } else if (item.getType().equals(NewsType.CLUE)) {
                intent = new Intent(context, PaikeActivity.class);
                intent.putExtra("id", item.getId());
            }
            if (intent != null) {
                startActivity(intent);
            }
        }
    };

    private void getList() {
        String url = Api.URL_SBSCRIBE_MY + "?page=" + page;
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                afterRequest();
                layEmpty.setVisibility(View.VISIBLE);
            }

            @Override
            public void onResponse(String response, int id) {
                int count = 0;
                afterRequest();
                ArrayList<NewsItemBean> data = JSONUtils.requestList(response, "data.docs", new TypeToken<ArrayList<NewsItemBean>>() {
                });
                if (page == 1) {
                    if (data == null || data.size() == 0) {
                        layEmpty.setVisibility(View.VISIBLE);
                        return;
                    }
                    count = JSONUtils.filterInt(response, "data.total", 0);
                    if (headerView == null) {
                        headerView = new SubsHeaderView(context);

                        Log.i(TAG, "count=" + count);
                        headerView.setData(count);
                        headerView.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivityForResult(new Intent(context, AddSubscribeActivity.class), REQUEST_ADD);
                            }
                        });
                        adapter.setHeaderView(headerView, rvList);
                    }
                    headerView.setData(count);
                    list = data;
                    adapter.setData(list);
                } else {
                    if (data == null || data.size() == 0) {
                        Toast.makeText(context, R.string.no_more, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (list == null) {
                        return;
                    }
                    list.addAll(data);
                    adapter.setData(list);
                }
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void afterRequest() {
        layLoading.setVisibility(View.GONE);
        layEmpty.setVisibility(View.GONE);
        if (page == 1) {
            xRefreshView.stopRefresh();
        } else {
            xRefreshView.stopLoadMore();
        }
    }

    private void add() {
        UserBean user;
        int mCode;
        Intent intent;
        user = ((MyApplication) getActivity().getApplication()).getUser();
        if (user == null) {
            mCode = REQUEST_LOGIN;
            intent = new Intent(context, LoginActivity.class);
        } else {
            mCode = REQUEST_ADD;
            intent = new Intent(context, AddSubscribeActivity.class);
        }
        startActivityForResult(intent, mCode);
    }

    private void refresh() {
        page = 1;
        layEmpty.setVisibility(View.GONE);
        layLoading.setVisibility(View.VISIBLE);
        getList();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "resultCode:" + resultCode);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_LOGIN:
                    refresh();
                    break;
                case REQUEST_ADD:
                    refresh();
                    break;
                default:
                    break;
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onMessage(ChangeUserInfoEvent event) {
        refresh();
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
}
